package com.yexx.starter.optms.idempotent.keygen.impl;

import com.yexx.starter.optms.idempotent.IdempotentProperties;
import com.yexx.starter.optms.idempotent.annotation.Idempotent;
import com.yexx.starter.optms.idempotent.keygen.LockKeyGenerator;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieLockKeyResolver implements LockKeyGenerator {

    private IdempotentProperties idempotentProperties;

    public CookieLockKeyResolver(IdempotentProperties idempotentProperties) {
        this.idempotentProperties = idempotentProperties;
    }

    @Override
    public String resolver(Idempotent idempotent, HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) {
        String lockKey = NOT_FOUND;
        if (StringUtils.hasText(idempotentProperties.getDefaultCookieLockKey())) {
            Cookie cookie = WebUtils.getCookie(request, idempotentProperties.getDefaultCookieLockKey());
            if (cookie != null) {
                lockKey = cookie.getValue();
            }
        }
        return String.format("%s_%s", lockKey, request.getRequestURI());
    }
}